package cn.kxm.controller;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.kxm.pojo.*;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;

import cn.kxm.service.CompanyService;
import cn.kxm.service.OutstorageBillService;
import cn.kxm.service.PartService;
import cn.kxm.util.ExcelUtil;
import cn.kxm.util.MakeNewCode;

@Controller
@RequestMapping("/osb")
public class OutstorageBillController extends BaseController{

	@Autowired
	private PartService ps;
	@Autowired
	private CompanyService cs;
	@Autowired
	private OutstorageBillService os;
	@Autowired
	private MakeNewCode mc;
	
	@RequestMapping("show")
	@ResponseBody
	public Object show(
			@RequestParam(value="findcode",required=false)String code,
			@RequestParam(value="findstartDate",required=false)String start,
			@RequestParam(value="findendDate",required=false)String end,
			@RequestParam(value="findsupplierName",required=false)String name,
			Integer page,Integer rows){
		int total=os.getCount(code,start,end,name);
		List<OutstorageBill> list=new ArrayList<OutstorageBill>();
		list=os.findAll(code,start,end,name,(page-1)*rows,rows);
		Map<String, Object> map=new HashMap<String, Object>();
		
		int amount=0;
		int money=0;
		for (OutstorageBill o : list) {
			amount+=o.getAmount();
			money+=o.getMoney();
		}
		OutstorageBill o=new OutstorageBill();
		o.setAmount(amount);
		o.setMoney(money);
		o.setCustomName("合计");
		o.setCode("true");
		OutstorageBill[] oo={o};
		map.put("footer", oo);
		map.put("rows", list);
		map.put("total", total);
		return JSONArray.toJSONString(map);
	}
	@RequestMapping("company")
	@ResponseBody
	public Object company(
			@RequestParam(value="findcode",required=false)String code,
			@RequestParam(value="findsupplierName",required=false)String name,
			@RequestParam(value="findtype",required=false)Integer type,
			Integer page,Integer rows){
		int total=cs.getCount(code,name,type);
		List<Company> list =cs.findAll(code,name,type,(page-1)*rows, rows);
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("total", total);
		map.put("rows", list);
		return JSON.toJSONString(map);
	}
	
	@RequestMapping("/findallpart")
	@ResponseBody
	public Object findAllPart(@RequestParam(value="partBrand",required=false)String partBrand,
			@RequestParam(value="partNo",required=false)String partNo,
			@RequestParam(value="partName",required=false)String partName,
			@RequestParam(value="partTypeId",required=false)Integer partTypeId,
			Integer page,Integer rows){
		List<Part> list=ps.getPartList(partBrand, partNo, partName, partTypeId, (page-1)*rows, rows);
		int total=ps.getPartCount(partBrand, partNo, partName, partTypeId);
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("total",total);
		map.put("rows",list);
		return JSONArray.toJSONString(map);
	}
	@RequestMapping("findpart")
    @ResponseBody
    public Object findAllTypeName(){
		
    	List<PartType> list=ps.getPartTypeList();
    	return JSON.toJSONString(list);
    }
	
	@RequestMapping("findone")
	public String findone(String code,Model model){
		OutstorageBill oBill=os.findByCode(code);
		model.addAttribute("oB", oBill);
		return "web/goods/showOuttorageBill";
	}
	@RequestMapping("modifyone")
	public String modifyone(String code,Model model){
		OutstorageBill oBill=os.findByCode(code);
		model.addAttribute("oB", oBill);
		return "web/goods/modifyOuttorageBill";//未审核
	}
	@RequestMapping("modifytwo")
	public String modifytwo(String code,Model model){
		OutstorageBill oBill=os.findByCode(code);
		model.addAttribute("oB", oBill);
		return "web/goods/modifyOntorageBill";//已审核
	}
	@RequestMapping("code")
	@ResponseBody
	public Object code(String prefix){
		Map<String, Object> map=new HashMap<String, Object>();
		String code=mc.getRandomCodeByPrefix(prefix);
		map.put("result", code);
		return JSONArray.toJSONString(map);
	}
	@RequestMapping("getpart")
	@ResponseBody
	public Object getpart(String code){
		List<Map<String, Object>> list=os.getPart(code);
		System.out.println(list.get(0).get("ordercode"));
		return JSONArray.toJSONString(list);
	}
	@RequestMapping("add")
	@ResponseBody
	public Object add(OutstorageBill o,String data){
		Map<String, Object> map=new HashMap<String, Object>();
		if(os.addoB(o)!=1){
			map.put("result", "error");
			return JSON.toJSONString(map);
		}
		List<Map<String, Object>> list=(List<Map<String, Object>>) JSON.parse(data);
		if(list!=null){
			for(int i=0;i<list.size()-1;i++){
				Map<String, Object> m=list.get(i);
				OutstorageBillDetail obd=new OutstorageBillDetail();
				obd.setAmount(Integer.parseInt(m.get("amount").toString()));
				obd.setPartCode(m.get("code").toString());
				obd.setPrice(Double.parseDouble(m.get("price").toString()));
				obd.setBillCode(o.getCode());
				if(m.get("ordercode")!=null){
					obd.setOrderCode(m.get("ordercode").toString());
				}
				if(m.get("memo")!=null){
					 obd.setMemo(m.get("memo").toString());
				}
				if(os.addoBdetail(obd)!=1){
					map.put("result", "error");
					return JSON.toJSONString(map);
				}
			}
		}else{
			map.put("result", "error");
			return JSON.toJSONString(map);
		}
		map.put("result", "success");
		return JSON.toJSONString(map);
	}
	@RequestMapping("modify")
	@ResponseBody
	public Object modify(OutstorageBill o,String data){
		Map<String, Object> map=new HashMap<String, Object>();
		if(os.modifyoB(o)!=1){
			map.put("result", "error");
			return JSON.toJSONString(map);
		}
		List<Map<String, Object>> list=(List<Map<String, Object>>) JSON.parse(data);
		if(list!=null){
			os.deleteoBdetail(o.getCode());//通过billcode删除明细
				//循环添加
				for (int i = 0; i < list.size()-1; i++) {
					Map<String,Object> m=list.get(i);
					OutstorageBillDetail obd=new OutstorageBillDetail();
					obd.setAmount(Integer.parseInt(m.get("amount").toString()));
					obd.setPartCode(m.get("code").toString());
					obd.setPrice(Double.parseDouble(m.get("price").toString()));
					obd.setBillCode(o.getCode());
					if(m.get("ordercode")!=null){
						obd.setOrderCode(m.get("ordercode").toString());
					}
					if(m.get("memo")!=null){
						 obd.setMemo(m.get("memo").toString());
					}
					if(os.addoBdetail(obd)>0){
						map.put("result", "success");
					}else{
						map.put("result", "error");
						return JSON.toJSONString(map);
					}
				}
			
		}else{
			map.put("result", "error");
			return JSON.toJSONString(map);
		}
		
		return JSON.toJSONString(map);
	}
	@RequestMapping("delete")
	@ResponseBody
	public Object delete(String code){
		Map<String, Object> map=new HashMap<String, Object>();
		if(os.deleteoBdetail(code)>0&&os.deleteoB(code)>0){//先删除涉及外键的详单
			map.put("result", "success");
		}else{
			map.put("result", "error");
		}
		return JSON.toJSONString(map);
	}
	@RequestMapping("del")
	@ResponseBody
	public Object del(String codes){
		Map<String, Object> map=new HashMap<String, Object>();
		List<String> list=(List<String>) JSON.parse(codes);
		for (String code: list) {
			if(os.deleteoBdetail(code.toString())>0&&os.deleteoB(code.toString())>0){//先删除涉及外键的详单
				map.put("result", "success");
			}else{
				map.put("result", "error");
			}
		}
		return JSON.toJSONString(map);
	}
	@RequestMapping("findsell")
	@ResponseBody
	public Object findsell(
			@RequestParam(value="findcode",required=false)String code,
			@RequestParam(value="findstartDate",required=false)String start,
			@RequestParam(value="findendDate",required=false)String end,
			@RequestParam(value="findsupplierName",required=false)String name,
			Integer page,Integer rows){
		int total =os.sellcount(code,name,start, end);
		List<Map<String, Object>> list=os.findsell(code,start, end,name,(page-1)*rows,rows);
		
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("total", total);
		map.put("rows", list);
		return JSON.toJSONString(map);
	}
	@RequestMapping("addsellpart")
	@ResponseBody
	public Object addsellpart(String data){
		List<Map<String, Object>> list=(List<Map<String, Object>>) JSON.parse(data);
		
		//List<List<Map<String, Object>>> l=new ArrayList<List<Map<String,Object>>>();
		List<Map<String, Object>> partlist=new ArrayList<Map<String,Object>>();
		for (Map<String, Object> map : list) {
			partlist.addAll(os.getSellPart(map.get("code").toString()));
		}
		return JSON.toJSONString(partlist);
	}
	@RequestMapping("upstatus")
	@ResponseBody
	public Object status(Integer status,String outcode,String data){
		System.out.println(status);
		Map<String, Object> map=new HashMap<String, Object>();
		boolean flag=true;
		List<Map<String, Object>> list=(List<Map<String, Object>>) JSON.parse(data);
		for (int i = 0; i < list.size()-1; i++) {
			Map<String, Object> m=list.get(i);
			String sellcode=null;
			if(m.get("ordercode")!=null){
				 sellcode=m.get("ordercode").toString();
				 int a=os.findoutstatus(sellcode);
				 if(a==2&&status==2){
					 map.put("result", "repeat");
					 flag=false;
					 break;
				 }
			}
		}
		for (int i = 0; i < list.size()-1; i++) {
			Map<String, Object> m=list.get(i);
			String partCode=(String) m.get("code");
			int amount=Integer.parseInt(m.get("amount").toString());
			if(amount>os.findamount(partCode)){
				map.put("result", "less");
				map.put("code", partCode);
				flag=false;
				break;
			}
		}
		if(flag){
			for (int i = 0; i < list.size()-1; i++) {
			Map<String, Object> m=list.get(i);
			String sellcode=null;
			if(m.get("ordercode")!=null){
				 sellcode=m.get("ordercode").toString();
			}
			int amount=Integer.parseInt(m.get("amount").toString());
			int avg=(Integer) m.get("avg");
			String partCode=(String) m.get("code");
			double sellPrice=avg;
			System.out.println(status+"====="+sellcode);
			boolean x=os.updateAll(status, outcode, amount, sellPrice, partCode,sellcode);
				if(x){
					map.put("result", "success");
				}else{
					map.put("result", "error");
				}
			}
		}	
		return JSON.toJSONString(map);
	}
	
	//2018年10月11日17点04分
	@RequestMapping("test")
	@ResponseBody
	public Object testChineseWord(String code){
		System.out.println(code);
		return JSON.toJSONString("000");
	}
	
	@RequestMapping("getExcel")
	public void export(HttpServletRequest request,HttpServletResponse response,
			@RequestParam("findcode") String findcode,
			@RequestParam("findstartDate") String findstartDate,
			@RequestParam("findendDate") String findendDate,
			@RequestParam("findsupplierName") String findsupplierName) throws Exception {
		List<OutstorageBill> list=new ArrayList<OutstorageBill>();
		list=os.findout(findcode,findstartDate,findendDate,findsupplierName);
		Map<String, Object> map=new HashMap<String, Object>();
		
		int amount=0;
		int money=0;
		for (OutstorageBill o : list) {
			amount+=o.getAmount();
			money+=o.getMoney();
		}
		//excel标题
		String[] title= {"出库单号","出库日期","单位名称","付款金额","审核状态","支付状态","备注"};
		//excel文件名
		String fileName="出库单据管理"+new Date()+".xls";		
		//sheet名
		String sheetName="出库单据管理";
		
		String[][] content=new String[list.size()][title.length];
		for(int i=0;i<list.size();i++) {
			OutstorageBill o=list.get(i);
			content[i][0]=o.getCode();
			content[i][1]=o.getOutstorageDate().toString();
			content[i][2]=o.getCustomName();
			content[i][3]=String.valueOf(o.getMoney());
			if(o.getCheckStatus()==1){
				content[i][4]="未审核";
			}else{
				content[i][4]="已审核";
			}
			if(o.getPayStatus()==1){
				content[i][5]="未支付";
			}else{
				content[i][5]="已支付";
			}
			content[i][6]=o.getMemo();
		}
		//创建HSSF
		HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
		//响应到客户端
		try {
			this.setResponseHeader(response, fileName);
			OutputStream os=response.getOutputStream();
			wb.write(os);
			os.flush();
			os.close();
		} catch(Exception e) {
			e.printStackTrace();
		}		
	}
	/** 
	 * @Title: setResponseHeader 
	 * @Description: 发送响应流方法
	 * @param response
	 * @param fileName  参数说明 
	 * @return void    返回类型 
	 * @throws 
	 */
	public void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(),"ISO8859-1");
			}catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		}catch(Exception ex) {
			ex.printStackTrace();
		}
	}
	
}
